<?php
// $Id$

/**
 * Controller_Press 控制器
 */
class Controller_Press extends Controller_Abstract
{

	//display by $_GET['id']
	function actionIndex()
	{
		if(!isset($_GET['id'])){
			$this->actionAll();
		}else{
			$this->actionP();
		}
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
	}
	
	//display top10 order by score
	function actionTop(){
		$this->_view['location'] = 'press';
	}
	
	function actionP(){
		$this->_view['haveHelper'] = true;
		$this->_view['location'] = 'press';
		
		if (QValidator::validate_is_digits($_GET['id'])){
			$id = intval($_GET['id']);
			$sql = "select sec_press.id, title, press, press_time, src, press, view, view_time,
				name as username, nickname, link, tags 
				from sec_press, user 
				where sec_press.id = $id and user_id = user.id";
			$res = DB::query($sql);
			if($row = $res->fetch_assoc()){
				$this->_view['p'] = $row;
			}
			
			$sql = "select name, id 
				from sec_press_relation, sec
				where sec_press_relation.press_id = $id and sec_id = sec.id";
			$res = DB::query($sql);
			$rs = array();
			while($row = $res->fetch_assoc()){
				$rs[] = $row;
			}
			
			$comments = array();
			$sql = "select comment, nickname, name as username, comment_time
			     from press_comment, user
			     where press_comment.user_id = user.id and 
			         press_id = $id
			     order by comment_time asc";
			$res = DB::query($sql);
			while($row = $res->fetch_assoc()){
				$comments[] = $row;
			}
			
			$this->_view['comments'] = $comments;
			$this->_view['rs'] = $rs;
			
		}else{
			return $this->_redirect(url("press"));
		}
	}
	
	function actionComment(){
	    if(!in_array("member", Q::registry('app')->currentUserRoles())){
            return $this->_redirect(url("user/login"));
        }else{
            $user = Q::registry("app")->currentUser();
        }
        
        if($this->_context->isPOST()){
        	$id = intval($_POST['id']);
        	if($id == $_POST['id']){
        		$res = DB::query("select id from sec_press where id = '$id'");
        		if ($row = $res->fetch_assoc()){
        			$content = trim($_POST['comment']);
        			if (mb_strlen($content) > 1200){
        				$content = mb_substr($content, 0, 1200, 'utf-8');
        			}
        			$content = DB::real_escape($content);
        			if (mb_strlen($content) > 0){
        				$query = "insert into press_comment (press_id, comment, user_id, comment_time)
                             values('$id', '$content', '{$user['id']}', now())";
                        DB::query($query);
        			}
        			return $this->_redirect(url("press/p", "id/$id"));
        		}
        	}
        }
        return $this->_redirect(url("press"));
	}
	
	//display all order by public time
	function actionAll(){
		$this->_view['location'] = 'press';
		$this->_view['haveHelper'] = true;
		
		$sql = "select title, press, id, press_time 
				from sec_press
				order by press_time desc, view_time desc
				limit 10";
		$res = DB::query($sql);
		$oldDate = '0';
		$presses = array();
		while($row = $res->fetch_assoc()){
			if ($row['press_time'] != $oldDate){
				$row['date'] = $row['press_time'];
				$oldDate = $row['press_time'];
			}
			if (mb_strlen($row['press'], 'utf-8') > 108 ){
				$row['press'] = mb_substr($row['press'], 0, 108, "utf-8") . "...";
			}
			$presses[] = $row;
		}
		
		$this->_view['presses'] = $presses;
	}
	
	
	/**
	 * 对表单数据进行验证，将验证结果输出到$errMsg中
	 * 返回的$errMsg结果为数组，比如： array('不能为空', '字符太长');
	 *
	 * @param array $errMsg
	 * 
	 * @return bool 是否验证成功, 没有问题返回true,有问题（错误）返回false
	 */
	function checkPressAddForm(& $errMsg){
		//validation
		$rules = array();
		$rules['link'] = array(
			array('is_url', true),
			array('max_iconv_length', 240)
		);
		$rules['press'] = array(
			array('not_null'),
			array('max_iconv_length', 240)
		);
		$rules['date'] = array(
			array('is_date')
		);
		$rules['tags'] = array(
			array('max_iconv_length', 48)
		);
		$rules['view'] = array(
			array('max_iconv_length', 240)
		);
		
		$rulesMsg= array('link' => array('is_url' => 'url链接无效', 'max_iconv_length' => '提供的url地址太长，不能超过240个字'),
					'press' => array( 'not_null'=>'新闻不能空', 'max_iconv_length'=> '小新闻字数不能超过240个字'),
					'date' => array( 'is_date'=>'请按格式输入日期（比如2009-09-09）'),
					'tags' => array( 'max_iconv_length'=> '标签最长不能超过48个字'),
					'view' => array('max_iconv_length'=> '评论字数不能超过240个字'),
		);
		
		return parent::formValidate($_POST, $rules, $rulesMsg, $errMsg);
	}
	
	
	function actionAdd(){
		$this->_view['location'] = 'press';
		//check whether is login
		if(!in_array("member", Q::registry('app')->currentUserRoles())){
			return $this->_redirect(url("user/login"));
		}else{
			$user = Q::registry("app")->currentUser();
		}
		$errMsg = array();
		
		//if add post
		if ($this->_context->isPOST()){
		
			//为了和javascript中验证字符串长度相同
			$_POST['view'] = str_replace("\r\n", "\n", $_POST['view']);
			$_POST['press'] = str_replace("\r\n", "\n", $_POST['press']);
			
			if($this->checkPressAddForm($errMsg)){
				//insert into database
				$link = DB::real_escape($_POST['link']);
				$press = DB::real_escape($_POST['press']);
				$date = trim($_POST['date']);
				$tags = DB::real_escape($_POST['tags']);
				$view = DB::real_escape($_POST['view']);
				$taga = Q::normalize(split(",|，| ", $tags));
				$tags = join("，", $taga);
				
				
				$aliasEquals = array();
				if (!empty($taga)){
					foreach($taga as $t){
						$aliasEquals[] =  "alias = '$t'";
					}
					$aeSql = join(" or ", $aliasEquals);
					$sql = "select distinct sec_id from sec_alias where $aeSql";
					$res = DB::query($sql);
					$sids = array();
					while($row = $res->fetch_assoc()){
						$sids[] = $row['sec_id'];
					}
				}
				DB::begin();
				$sql = "insert into sec_press
					(press, press_time, link, tags,view, view_time, user_id)
					values
					('$press', '$date', '$link', '$tags', '$view',
					 now(), {$user['id']})";
				DB::query($sql);
				
				$id = DB::insert_id();
				
				if (!empty($sids)){
					$values = "";
					$updates = "";
					foreach($sids as $sid){
						$values .= "($id, $sid),";
						$updates .= "id = $sid or ";
					}
					$updates .= "id = $sid";
					$values = trim($values, ",");
					$sql = "insert into sec_press_relation (press_id, sec_id)
						values $values";
					DB::query($sql);
					
					$sql = "update sec_sum 
						set press_cnt = press_cnt + 1
						where $updates";
					DB::query($sql);
				}
				
				DB::commit();
				return $this->_redirect(url("press/p", "id/$id"));
			}
		}
		
		$this->_view['errMsg'] = $errMsg;
	}
	
	
	function actionEditShow(){
		//check whether is logged in
		
		//if have $_GET['id'], the tags should have the secname
		
		//display the form
	}
	
	
	function actionEdit(){
		//check whether is logged in
	
	}
	
	function actionDelete(){
		//check whether is logged in
		
		
	}
}


